package cn.mill.support.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHandler {
	private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);
	
	public static InputStream get(String uri, Header[] headers, int connectTimeout, int socketTimeout) throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = (CloseableHttpClient) HttpConnectionManager.getHttpClient();
		RequestConfig requestConfig = HttpHandler.getRequestConfig(connectTimeout, socketTimeout);
		logger.debug("============================HttpHandler====================================");
		// CloseableHttpResponse httpResponse = null;
		HttpGet httpGet = new HttpGet(uri);
		httpGet.setConfig(requestConfig);
		if (headers != null) {
			for (Header header : headers) {
				httpGet.addHeader(header);
			}
		}
		HttpEntity entity = httpClient.execute(httpGet).getEntity();
		return entity == null ? null : entity.getContent();
	}
	
	public static InputStream post(String uri, Header[] headers, String message, int connectTimeout, int socketTimeout, boolean isReTry) throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = null;
		if (isReTry) {
			httpClient = (CloseableHttpClient) HttpConnectionManager.getHttpClient();
		} else {
			httpClient = (CloseableHttpClient) HttpConnectionManager.getHttpClient();
		}
		RequestConfig requestConfig = HttpHandler.getRequestConfig(connectTimeout, socketTimeout);
		
		// CloseableHttpResponse httpResponse = null;
		HttpPost httpPost = new HttpPost(uri);
		if (message == null || message.isEmpty()) {
			return null;
		}
		StringEntity inputEntry = new StringEntity(message, "UTF-8");
		httpPost.setEntity(inputEntry);
		httpPost.setConfig(requestConfig);
		if (headers != null) {
			for (Header header : headers) {
				httpPost.addHeader(header);
			}
		}
		HttpEntity entity = httpClient.execute(httpPost).getEntity();
		return entity == null ? null : entity.getContent();
	}
	
	private static RequestConfig getRequestConfig(int connectTimeout, int socketTimeout) {
		if (socketTimeout <= 0 || socketTimeout > 120000) {
			socketTimeout = 30000;
		}
		if (connectTimeout <= 0 || connectTimeout > 12000) {
			connectTimeout = 3000;
		}
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout) // 读取超时
				.setConnectTimeout(connectTimeout) // 连接超时
				.build(); // 设置请求和传输超时时间
		return requestConfig;
	}
}
